#coding=utf8

import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from case.test_app import TestApp


from page.find_element_class import Find_UI_Element

from base.mult_servers import Mult_start
from base.server_auto_start import Server
from base.get_driver import Driver
from base.package_divice_capacity import Relation
from util.configer_generator import configer
import multiprocessing
from util.Handle_Install_Window import Handle_Install_Window

def test_suite(device, webview_version, caps,p_port):#cases_list=[[],[],[]]
    D=Driver(device,webview_version,caps)
    res=Relation.find_Package(device, D.caps["appPackage"])
    if(res!=True):
        install_btn=configer.get_str("button_name","install_button_name")
    # right_btn=configer.get_str("button_name","right_button_name")
    # right_button_times=configer.get_int("button_name","right_button_name_times")
    # print(name+"**********************************")
        th=multiprocessing.Process(target=Handle_Install_Window,args=(p_port,D.caps1,install_btn))
        th.start()
    D.create_driver(p_port)
    if(res!=True):
        th.join()
    test_app=TestApp(D.driver)
    test_app.run()





if __name__=="__main__":
    flag=configer.get_str("if_install_auto", "flag")
    if  flag== "package":
        p_list=[]
        rel=Relation()
        ms = Mult_start()
        ms.start_servers_threads()
        devices_list=ms.device_list
        webview_dic = rel.device_webview  # 得到设备和webview的字典，为后续的driver启动提供参数
        cap_dic = rel.device_capacity  # 得到设备和ini文件中的capacity的字典，为后续的driver启动提供参数
        package_dic = rel.device_package  # 获得设备和app包名的字典
        p_port_dic=ms.driver_args_lsit#获得设备与p_port的字典
        print(rel.device_capacity)
    elif flag=="apk":
        p_list = []
        rel = Relation()
        ms = Mult_start()
        ms.start_servers_threads()
        devices_list = ms.device_list
        webview_dic = rel.device_webview  # 得到设备和webview的字典，为后续的driver启动提供参数
        cap_dic = rel.apk_device_capacity  # 得到设备和ini文件中的capacity的字典，为后续的driver启动提供参数
        package_dic = rel.device_apk_package  # 获得设备和app包名的字典
        p_port_dic = ms.driver_args_lsit  # 获得设备与p_port的字典


    for i in range(len(devices_list)):
        print(webview_dic)
        device =devices_list[i]
        package=package_dic[device]
        webview_version=webview_dic[device]
        caps=cap_dic[device]
        p_port=p_port_dic[device]
        #注意使用多进程时有些对象不能被序列化，例如此处的driver，因此driver不能作为参数传到进程对象
        p=multiprocessing.Process(target=test_suite,args=(device,webview_version,caps,p_port))#包名需加.xls才是用例的excel名
        p_list.append(p)
        p.start()
    for j in p_list:
        j.join()#等待所有的进程执行完用例
    Server("node.exe").kill_Server()








